package com.woniuxy.micropermissionserver.adminmanage.controller;

import com.woniuxy.microcommonserver.bean.permission_hcz.Admin;
import com.woniuxy.microcommonserver.bean.permission_hcz.Role;
import com.woniuxy.microcommonserver.pageHelper.PageRequest;
import com.woniuxy.microcommonserver.pageHelper.TableResult;
import com.woniuxy.microcommonserver.res.ResultMsg;
import com.woniuxy.micropermissionserver.adminmanage.service.IAdminService;
import com.woniuxy.micropermissionserver.rolemanage.service.IRoleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private IAdminService adminService;

    @Resource
    private IRoleService roleService;


    @GetMapping("validateLoginName/{loginName}")
    public boolean validateLoginName(@PathVariable("loginName") String loginName) {
        return adminService.login(loginName) == null;
    }

    @GetMapping
    public ResultMsg addAdminForm() {
        List<Role> roles = roleService.findAll();
        Map<String, Object> map = new HashMap<>();
        map.put("roles", roles);
        map.put("posts", new String[]{});
        return ResultMsg.builder().code(200).msg("success").data(map).build();
    }


    @PostMapping("/add")
    public ResultMsg addAdmin(@RequestBody Admin admin) {
        adminService.addAdmin(admin, admin.getRoleIds());
        return new ResultMsg(200, "success", null);
    }


    @GetMapping("/{id}")
    public ResultMsg<Admin> findById(@PathVariable("id") Integer id) {
        return new ResultMsg<>(200, "success", adminService.findById(id));
    }

    @GetMapping("list")
    public ResultMsg<TableResult<Admin>> list(PageRequest page, Admin admin) {
        return ResultMsg.<TableResult<Admin>>builder().msg("success").code(200).data(adminService.findPage(page, admin)).build();
    }
}
